﻿using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace AccountManagement
{
    /// <summary>
    /// Interaction logic for FrmOptions.xaml
    /// </summary>
    public partial class FrmOptions : Window
    {
        private bool _isValidated;

        public FrmOptions()
        {
            InitializeComponent();
            _isValidated = true;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!_isValidated)
                {
                    MessageBox.Show("Nhập sai định dạng, xem chi tiết các ô màu đỏ.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // Build Connection string
                // "Data Source=LINH-PC;Initial Catalog=AccountsDB;Persist Security Info=True;User ID=sa;Password=abcde123456"
                var connection = new SqlConnectionStringBuilder
                                     {
                                         DataSource = txtServerName.Text.Trim(),
                                         InitialCatalog = txtDBName.Text.Trim(),
                                         PersistSecurityInfo = true,
                                         UserID = txtUser.Text.Trim(),
                                         Password = txtPass.Password
                                     };

                // So Phieu
                var oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                oConfig.AppSettings.Settings["QuyenSoPhieuThu"].Value = txtSoQuyenThu.Text.Trim();
                oConfig.AppSettings.Settings["PhieuSoPhieuThu"].Value = txtSoPhieuThu.Text.Trim();
                oConfig.AppSettings.Settings["QuyenSoPhieuChi"].Value = txtSoQuyenChi.Text.Trim();
                oConfig.AppSettings.Settings["PhieuSoPhieuChi"].Value = txtSoPhieuChi.Text.Trim();

                // Connection string config
                var connectionSection = oConfig.ConnectionStrings;
                connectionSection.ConnectionStrings["AccountManagement.Properties.Settings.AccountsConnectionString"].
                    ConnectionString = connection.ConnectionString;

                oConfig.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

                MessageBox.Show("Lưu thông tin cấu hình thành công.", "Thông báo", MessageBoxButton.OK,
                                MessageBoxImage.Information);
                Close();
            }
            catch (Exception)
            {
                
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var connection = ConfigurationManager.ConnectionStrings["AccountManagement.Properties.Settings.AccountsConnectionString"];
                var connStr = connection.ConnectionString.Split(';');

                txtServerName.Text = connStr[0].Substring(connStr[0].IndexOf("=") + 1);
                txtDBName.Text = connStr[1].Substring(connStr[1].IndexOf("=") + 1);
                txtUser.Text = connStr[3].Substring(connStr[3].IndexOf("=") + 1);
                txtPass.Password = connStr[4].Substring(connStr[4].IndexOf("=") + 1);

                txtSoPhieuThu.Text = ConfigurationManager.AppSettings.Get("PhieuSoPhieuThu");
                txtSoQuyenThu.Text = ConfigurationManager.AppSettings.Get("QuyenSoPhieuThu");
                txtSoPhieuChi.Text = ConfigurationManager.AppSettings.Get("PhieuSoPhieuChi");
                txtSoQuyenChi.Text = ConfigurationManager.AppSettings.Get("QuyenSoPhieuChi");
            }
            catch (Exception)
            {
                
            }
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                var textBox = (TextBox)sender;
                if (textBox == null) return;

                //var regEx = new Regex(@"^[-+]?\d*\.?\d*$"); // Matches any floating point numer/numeric string, including optional sign character (+ or -). Also matches empty strings.
                //var regEx = new Regex(@"^(((\d{1,3})(,\d{3})*)|(\d+))(.\d+)?$"); // validates numbers, with or without decimal places, and comma 1000 separators.
                var regEx = new Regex(@"^[-+]?\d+(\.\d+)?$"); // This matches any real number, with optional decimal point and numbers after the decimal, and optional positive (+) or negative (-) designation.

                if (!regEx.IsMatch(textBox.Text.Trim()))
                {
                    textBox.BorderBrush = Brushes.Red;
                    textBox.ToolTip = "Chỉ được phép nhập số.";
                    _isValidated = false;
                }
                else
                {
                    textBox.BorderBrush = txtServerName.BorderBrush;

                    if (txtSoPhieuThu.BorderBrush != Brushes.Red &&
                        txtSoQuyenThu.BorderBrush != Brushes.Red &&
                        txtSoPhieuChi.BorderBrush != Brushes.Red &&
                        txtSoQuyenChi.BorderBrush != Brushes.Red)
                        _isValidated = true;
                }
            }
            catch (Exception)
            {

            }
        }
    }
}
